<!DOCTYPE html>
<html>
<head>
  <title>输入输出格式化</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="/bootstrap.min.css" rel="stylesheet">
  <style>
    .chat-container {
      height: 400px;
      overflow-y: auto;
      border: 1px solid #ddd;
      padding: 10px;
      margin-bottom: 10px;
    }

    .message {
      margin-bottom: 10px;
      padding: 10px;
      border-radius: 5px;
    }

    .user-message {
      background-color: #e3f2fd;
      margin-left: 20%;
    }

    .ai-message {
      background-color: #f5f5f5;
      margin-right: 20%;
    }
  </style>
</head>
<body>
<div class="container mt-5">
  <h2>输入输出格式化</h2>

  <!-- Chat Section -->
  <div class="card mb-4">
    <div class="card-header">
      聊天
    </div>
    <div class="card-body">
      <div class="chat-container" id="chatContainer"></div>
      <div class="input-group">
        <input type="text" class="form-control" value="go" id="messageInput" placeholder="输入消息...">
        <button class="btn btn-primary" onclick="sendMessage()">发送</button>
      </div>
    </div>
  </div>

</div>

<script>

  function appendMessage(message, isUser) {
    const chatContainer = document.getElementById('chatContainer');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
    messageDiv.textContent = message;
    chatContainer.appendChild(messageDiv);
    chatContainer.scrollTop = chatContainer.scrollHeight;
  }

  async function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    const message = messageInput.value.trim();
    if (!message) {
      return;
    }

    appendMessage(message, true);
    messageInput.value = '';

    try {
      const response = await fetch('/format/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `msg=${encodeURIComponent(message)}`
      });
      const reply = await response.text();
      appendMessage(reply, false);
    } catch (error) {
      console.error('Error:', error);
      appendMessage('发生错误，请稍后重试。', false);
    }
  }

  // 支持按回车发送消息
  document.getElementById('messageInput').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      sendMessage();
    }
  });
</script>
</body>
</html> 